package com.baidu.baiduyun;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadHandleServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	String serverPath = "http://bcs.duapp.com/pluto-coding";

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String url = request.getParameter("cp");
		String filename = "";
		try {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setHeaderEncoding("UTF-8");
			if (!ServletFileUpload.isMultipartContent(request)) {
				return;
			}
			List<FileItem> list = upload.parseRequest(request);
			for (FileItem item : list) {
				filename = item.getName();
				if (filename == null || filename.trim().equals("")) {
					continue;
				}
				filename = filename.substring(filename.lastIndexOf("\\") + 1);
				FileInputStream fis = (FileInputStream) (item.getInputStream());
				// 获取item中的上传文件的输入流
				InputStream in = item.getInputStream();
				File f = new File(filename);
				inputstreamtofile(in, f);

				{
					// 是否将文件保存到云端？
//					 Baidu.putObjectByFile(filename, f);
				}

//				Word2Html.convert2Html(fis, serverPath);
				item.delete();
			}
			request.setAttribute("success", "上传成功");
			url +=  "/?u="+serverPath;
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("success", "上传失败");
		}
		String upload = "http://192.168.1.108:8080/yunbaidu/servlet/UploadHandleServlet?cp=http://imessage.dk.edu.com/blog/message.jsp";
//		request.getRequestDispatcher("http://imessage.dk.edu.com/blog/message.jsp").forward(request, response);
		response.sendRedirect(url+"?filename="+filename);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

	public static void inputstreamtofile(InputStream ins, File file) {
		try {
			OutputStream os = new FileOutputStream(file);
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.close();
			ins.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
